package DatabaseAccessing;

import java.util.Iterator;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

public class ProductModelController {

    public void addProduct(Products p) {
        Transaction trans = null;
        Session session = SessionFactoryUtil.getInstance();
        try {
            trans = session.beginTransaction();
            session.persist(p);
            trans.commit();
        } catch (RuntimeException exp) {
            if (trans != null && trans.isActive()) {
                try {
                    trans.rollback();
                    System.err.println("Error(addProduct) Commit error: "
                            + exp.getMessage());
                } catch (HibernateException hibernateException) {
                    System.err.println("Error(addProduct) Rollback error: "
                            + hibernateException.getMessage());
                }
            }
        }
    }

    public void editProduct(Products p) {
        Transaction trans = null;
        Session session = SessionFactoryUtil.getInstance();
        try {
            trans = session.beginTransaction();
            Products newProduct = (Products) session.get(Products.class, p.getProductId());
            newProduct.setAmount(p.getAmount());
            newProduct.setPrice(p.getPrice());
            newProduct.setProductCategoryId(p.getProductCategoryId());
            newProduct.setProductImage(p.getProductImage());
            newProduct.setProductName(p.getProductName());
            newProduct.setProductNotes(p.getProductNotes());
            session.update(newProduct);
            trans.commit();
        } catch (RuntimeException exp) {
            if (trans != null && trans.isActive()) {
                try {
                    trans.rollback();
                    System.err.println("Error(editProduct) Commit error: "
                            + exp.getMessage());
                } catch (HibernateException hibernateException) {
                    System.err.println("Error(editProduct) Rollback error: "
                            + hibernateException.getMessage());
                }
            }
        }

    }

    public void deleteProduct(int id) {
        Transaction trans = null;
        Session session = SessionFactoryUtil.getInstance();
        try {
            trans = session.beginTransaction();
            Products newProduct = (Products) session.load(Products.class, new Integer(id));
            session.delete(newProduct);
            trans.commit();
        } catch (RuntimeException exp) {
            if (trans != null && trans.isActive()) {
                try {
                    trans.rollback();
                    System.err.println("Error(deleteProduct) Commit error: "
                            + exp.getMessage());
                } catch (HibernateException hibernateException) {
                    System.err.println("Error(deleteProduct) Rollback error: "
                            + hibernateException.getMessage());
                }
            }
        }

    }

    public Products viewProductByID(int id) {
        Products product = null;
        Session session = SessionFactoryUtil.getInstance();
        try {
            product = (Products) session.load(Products.class, new Integer(id));
        } catch (HibernateException hibernateException) {
            System.err.println("Error(viewProductByID) load error: "
                    + hibernateException.getMessage());
        }
        return product;

    }

    public List viewProductByName(String name) {
        Session session = SessionFactoryUtil.getInstance();
        List productList = null;
        try {
            Criteria nameCriteria = session.createCriteria(Products.class);
            nameCriteria.add(Restrictions.eq("productName", name));
            productList = nameCriteria.list();
        } catch (HibernateException hibernateException) {
            System.err.println("Error(viewProductByName) query error: "
                    + hibernateException.getMessage());
        }
        return productList;
    }

    public List viewProductByCategory(String category) {
        Session session = SessionFactoryUtil.getInstance();
        List products = null;
        try {
              String queryStr="from Products where productCategoryId=(select productCategoryId from Productcategory where categoryName='"+category+"' )";  // get customer by id

              Query queryRslt=session.createQuery(queryStr);

              products=queryRslt.list();
           // Iterator CategoryIterator = viewCategoryByName(category).iterator();
           // while (CategoryIterator.hasNext()) {
            //    Criteria nameProduct = session.createCriteria(Products.class);
             //   nameProduct.add(Restrictions.eq("productCategoryID",
             //           ((Productcategory) CategoryIterator.next()).getProductCategoryId()));
             //   products = nameProduct.list();
           // }
        } catch (HibernateException hibernateException) {
            System.err.println("Error(viewProductByCategory) query error: "
                    + hibernateException.getMessage());
        }
        return products;
    }

    public List viewSomeProduct(int pageNumber) {
        Session session = SessionFactoryUtil.getInstance();
        List products = null;
        try {
            Query q = session.createQuery("from Products p");
           // q.setMaxResults(10);
            products = q.list();
        } catch (HibernateException hibernateException) {
            System.err.println("Error(viewSomeProduct) query error: "
                    + hibernateException.getMessage());
        }
        return products;
    }

    public List viewAllProducts() {
        Session session = SessionFactoryUtil.getInstance();
        List products = null;
        try {
            Query q = session.createQuery("from Products");
            products = q.list();
        } catch (HibernateException hibernateException) {
            System.err.println("Error(viewAllProducts) query error: "
                    + hibernateException.getMessage());
        }
        return products;
    }

    public List viewCategoryByName(String name) {
        Session session = SessionFactoryUtil.getInstance();
        List categoryList = null;
        try {
            Criteria nameCriteria = session.createCriteria(Productcategory.class);
            nameCriteria.add(Restrictions.eq("categoryName", name));
            categoryList = nameCriteria.list();
        } catch (HibernateException hibernateException) {
            System.err.println("Error(viewCategoryByName) query error: "
                    + hibernateException.getMessage());
        }
        return categoryList;
    }

    public Productcategory viewCategoryByID(int id) {
        Session session = SessionFactoryUtil.getInstance();
        Productcategory category = null;
        try {
            category = (Productcategory) session.load(Productcategory.class, new Integer(id));
        } catch (HibernateException hibernateException) {
            System.err.println("Error(viewCategoryByID) query error: "
                    + hibernateException.getMessage());
        }
        return category;

    }

    public void addCategory(Productcategory c) {
        Session session = SessionFactoryUtil.getInstance();
        Transaction trans = null;
        try {
            trans = session.beginTransaction();
            session.persist(c);
            trans.commit();
        } catch (RuntimeException exp) {
            if (trans != null && trans.isActive()) {
                try {
                    trans.rollback();
                    System.err.println("Error(addCategory) Commit error: "
                            + exp.getMessage());
                } catch (HibernateException hibernateException) {
                    System.err.println("Error(addCategory) Rollback error: "
                            + hibernateException.getMessage());
                }
            }
        }
    }

    public void editCategory(Productcategory c) {
        Session session = SessionFactoryUtil.getInstance();
        Transaction trans = null;
        try {
            trans = session.beginTransaction();
            Productcategory newCategory = (Productcategory) session.get(Productcategory.class, c.getProductCategoryId());
            newCategory.setCategoryImage(c.getCategoryImage());
            newCategory.setCategoryName(c.getCategoryName());
            session.update(newCategory);
            trans.commit();
        } catch (RuntimeException exp) {
            if (trans != null && trans.isActive()) {
                try {
                    trans.rollback();
                    System.err.println("Error(editCategory) Commit error: "
                            + exp.getMessage());
                } catch (HibernateException hibernateException) {
                    System.err.println("Error(editCategory) Rollback error: "
                            + hibernateException.getMessage());
                }
            }
        }

    }

    public void deleteCategory(int id) {
        Session session = SessionFactoryUtil.getInstance();
        Transaction trans = null;
        try {
            trans = session.beginTransaction();
            Productcategory newCategory = (Productcategory) session.load(Productcategory.class, new Integer(id));
            session.delete(newCategory);
            trans.commit();
        } catch (RuntimeException exp) {
            if (trans != null && trans.isActive()) {
                try {
                    trans.rollback();
                    System.err.println("Error(deleteCategory) Commit error: "
                            + exp.getMessage());
                } catch (HibernateException hibernateException) {
                    System.err.println("Error(deleteCategory) Rollback error: "
                            + hibernateException.getMessage());
                }
            }
        }
    }

    /**
     * This function used to return all category
     * @return List
     */
    public List<Productcategory> viewAllCategorys()
    {
       Session session = SessionFactoryUtil.getInstance();
        List<Productcategory> productsCategory = null;
        try {
            Query q = session.createQuery("from Productcategory");
            productsCategory = q.list();
        } catch (HibernateException hibernateException) {
            System.err.println("Error(viewAllProductsCategory) query error: "
                    + hibernateException.getMessage());
        }
        return productsCategory;
    }



    /**
     * This function used to view special products
     * @return Products
     */
     public Products viewSpecialProduct()
    {
       Session session = SessionFactoryUtil.getInstance();
       Iterator proit=null;
       Products pro=null;
       //  List<Productcategory> productsCategory = null;
        try {

        Criteria cr=session.createCriteria(Products.class).setProjection(Projections.projectionList()
                .add(Projections.min("price")).add(Projections.property("productName"))
                .add(Projections.property("productImage"))
                .add(Projections.property("productNotes"))
                .add(Projections.property("price"))
                .add(Projections.property("productId"))
                );

      //  proit=cr.list().iterator();

      //  if(proit.hasNext())
      //  {
          Object [] obj=(Object []) cr.uniqueResult();   // (Object [])proit.next();
          pro=new Products();
          pro.setProductName(obj[1].toString());
          pro.setProductImage(obj[2].toString());
          pro.setProductNotes(obj[3].toString());
          pro.setPrice(Float.parseFloat(obj[4].toString()));
          pro.setProductId(Integer.parseInt(obj[5].toString()));
      //  }
       
        } catch (HibernateException hibernateException) {
            System.err.println("Error(viewAllProductsCategory) query error: "
                    + hibernateException.getMessage());
        }

        return pro;
    }
    
}
